<script setup lang="ts">
import type { LoginParams } from '@/api/interface/system/admin/login'
import { nextTick, onMounted, reactive, ref } from 'vue'
import { getCaptchaStatus } from '@/api/modules/system/admin/captcha'
import { loginApi } from '@/api/modules/system/admin/login'
import { getTenantEnableStatusApi } from '@/api/modules/system/tenant/tenant'
import { useUserStore } from '@/store/user'

// Store
const userStore = useUserStore()

// 响应式数据
const loading = ref(false)
const captchaEnabled = ref(false)
const tenantEnabled = ref(false)
const currentTenant = ref('')
const showPassword = ref(false)
const pageLoaded = ref(false)
const formVisible = ref(false)

// 登录表单
const loginForm = reactive({
  username: 'admin',
  password: '123456',
})

// 表单验证状态
const validation = reactive({
  username: { valid: true, message: '' },
  password: { valid: true, message: '' },
})

// 执行登录
async function performLogin() {
  loading.value = true

  // 添加触觉反馈（小程序）
  uni.vibrateShort()

  try {
    const loginParams: LoginParams = {
      ...loginForm,
      clientId: import.meta.env.VITE_APP_CLIENT_ID || 'web',
      grantType: 'password',
    }

    const { data } = await loginApi(loginParams)

    // 保存用户信息和token
    userStore.setUserInfo({
      id: data.userInfo.id || 0,
      username: data.userInfo.username,
      avatar: data.userInfo.logo || '/static/images/default-avatar.png',
      token: data.accessToken,
    })

    // 保存菜单类型
    if (data.menuType) {
      uni.setStorageSync('menuType', data.menuType)
    }

    // 成功反馈
    uni.vibrateShort()
    uni.showToast({
      title: '登录成功',
      icon: 'success',
      duration: 2000,
    })

    // 延迟跳转，让用户看到成功提示
    setTimeout(() => {
      uni.switchTab({
        url: '/pages/index/index',
      })
    }, 1500)
  } catch (error: any) {
    console.error('登录失败:', error)
    // 错误反馈
    uni.vibrateShort()
    uni.showToast({
      title: error.msg || '登录失败，请检查账号密码',
      icon: 'none',
      duration: 3000,
    })
  } finally {
    loading.value = false
  }
}

// 表单验证
function validateForm() {
  let isValid = true

  // 验证用户名
  if (!loginForm.username.trim()) {
    validation.username = { valid: false, message: '请输入用户名' }
    isValid = false
  } else if (loginForm.username.length < 3) {
    validation.username = { valid: false, message: '用户名至少3个字符' }
    isValid = false
  } else {
    validation.username = { valid: true, message: '' }
  }

  // 验证密码
  if (!loginForm.password.trim()) {
    validation.password = { valid: false, message: '请输入密码' }
    isValid = false
  } else if (loginForm.password.length < 6) {
    validation.password = { valid: false, message: '密码至少6个字符' }
    isValid = false
  } else {
    validation.password = { valid: true, message: '' }
  }

  return isValid
}

// 获取验证码状态
async function getCaptchaStatusInfo() {
  try {
    const { data } = await getCaptchaStatus()
    captchaEnabled.value = data.enable
  } catch (error) {
    console.error('获取验证码状态失败:', error)
  }
}

// 获取租户功能启用状态
async function getTenantEnableStatus() {
  try {
    const res = await getTenantEnableStatusApi()
    if (res.code === '0000' && res.data) {
      tenantEnabled.value = res.data.enable
      if (tenantEnabled.value) {
        currentTenant.value = uni.getStorageSync('tenantCode') || '默认租户'
      }
    }
  } catch (error) {
    console.error('获取租户功能启用状态失败:', error)
  }
}

// 处理登录
async function handleLogin() {
  if (!validateForm()) {
    uni.vibrateShort()
    return
  }
  await performLogin()
}

// 重置表单
function resetForm() {
  loginForm.username = ''
  loginForm.password = ''
  validation.username = { valid: true, message: '' }
  validation.password = { valid: true, message: '' }

  // 触觉反馈
  uni.vibrateShort()
}

// 跳转到注册页面
function goToRegister() {
  uni.vibrateShort()
  uni.navigateTo({
    url: '/pages/register/register',
  })
}

// 切换密码显示状态
function togglePasswordVisibility() {
  showPassword.value = !showPassword.value
  // 轻微触觉反馈
  uni.vibrateShort({ type: 'light' })
}

// 输入框聚焦处理
function handleInputFocus(field: string) {
  // 清除之前的错误状态
  if (field === 'username') {
    validation.username = { valid: true, message: '' }
  } else if (field === 'password') {
    validation.password = { valid: true, message: '' }
  }
}

// 页面加载动画
function startPageAnimation() {
  pageLoaded.value = true
  nextTick(() => {
    setTimeout(() => {
      formVisible.value = true
    }, 200)
  })
}

// 页面挂载
onMounted(() => {
  // 启动页面加载动画
  startPageAnimation()

  // 延迟调用API，避免阻塞动画
  setTimeout(() => {
    getCaptchaStatusInfo()
    getTenantEnableStatus()
  }, 800)
})
</script>

<template>
  <view class="login-page" :class="{ loaded: pageLoaded }">
    <!-- 动态背景 -->
    <view class="background-layer">
      <view class="gradient-overlay" />
      <view class="floating-elements">
        <view class="float-element element-1" />
        <view class="float-element element-2" />
        <view class="float-element element-3" />
        <view class="float-element element-4" />
      </view>
    </view>

    <!-- 主内容容器 -->
    <view class="main-container">
      <!-- 头部区域 -->
      <view class="header-area" :class="{ visible: pageLoaded }">
        <view class="logo-section">
          <view class="logo-ring">
            <image src="/static/logo.svg" class="logo-image" mode="aspectFit" />
          </view>
          <view class="title-group">
            <text class="app-name">Glowxq</text>
            <text class="app-subtitle">Nexus</text>
          </view>
        </view>
        <text class="welcome-text">欢迎回来</text>
      </view>

      <!-- 登录表单区域 -->
      <view class="form-container" :class="{ visible: formVisible }">
        <view class="form-card">
          <!-- 用户名输入 -->
          <view class="input-group" :class="{ error: !validation.username.valid }">
            <view class="input-wrapper">
              <view class="input-prefix">
                <wd-icon name="user" size="22px" color="#8E8E93" />
              </view>
              <input
                v-model="loginForm.username"
                placeholder="用户名"
                type="text"
                class="input-field"
                @focus="handleInputFocus('username')"
                @blur="validateForm"
              />
            </view>
            <text v-if="!validation.username.valid" class="error-message">
              {{ validation.username.message }}
            </text>
          </view>

          <!-- 密码输入 -->
          <view class="input-group" :class="{ error: !validation.password.valid }">
            <view class="input-wrapper">
              <view class="input-prefix">
                <wd-icon name="lock" size="22px" color="#8E8E93" />
              </view>
              <input
                v-model="loginForm.password"
                :password="!showPassword"
                placeholder="密码"
                class="input-field"
                @focus="handleInputFocus('password')"
                @blur="validateForm"
              />
              <view class="input-suffix" @tap="togglePasswordVisibility">
                <wd-icon :name="showPassword ? 'eye' : 'eye-close'" size="22px" color="#8E8E93" />
              </view>
            </view>
            <text v-if="!validation.password.valid" class="error-message">
              {{ validation.password.message }}
            </text>
          </view>

          <!-- 验证码提示 -->
          <view v-if="captchaEnabled" class="captcha-notice">
            <wd-icon name="info" size="16px" color="#FF9500" />
            <text class="captcha-text">需要验证码验证</text>
          </view>

          <!-- 登录按钮 -->
          <button
            class="login-button"
            :class="{ loading, disabled: loading }"
            :disabled="loading"
            @tap="handleLogin"
          >
            <view v-if="!loading" class="button-content">
              <wd-icon name="arrow-right" size="20px" color="#ffffff" />
              <text class="button-text">登录</text>
            </view>
            <view v-else class="loading-content">
              <wd-icon name="loading" size="20px" color="#ffffff" class="loading-icon" />
              <text class="button-text">登录中...</text>
            </view>
          </button>

          <!-- 辅助操作 -->
          <view class="form-actions">
            <text class="action-link" @tap="resetForm">重置表单</text>
            <text class="action-link primary" @tap="goToRegister">注册账号</text>
          </view>
        </view>
      </view>

      <!-- 租户信息 -->
      <view v-if="tenantEnabled" class="tenant-info" :class="{ visible: formVisible }">
        <view class="tenant-card">
          <wd-icon name="building" size="18px" color="#8E8E93" />
          <text class="tenant-label">租户</text>
          <text class="tenant-name">
            {{ currentTenant || '默认租户' }}
          </text>
        </view>
      </view>
    </view>

    <!-- 页面装饰 -->
    <view class="page-decoration">
      <view class="decoration-line line-1" />
      <view class="decoration-line line-2" />
    </view>
  </view>
</template>

<style lang="scss" scoped>
// 基础变量
$primary-color: #007aff;
$secondary-color: #5ac8fa;
$success-color: #34c759;
$warning-color: #ff9500;
$error-color: #ff3b30;
$text-primary: #1d1d1f;
$text-secondary: #8e8e93;
$text-tertiary: #c7c7cc;
$background-primary: #f2f2f7;
$background-secondary: #ffffff;
$border-color: rgba(60, 60, 67, 0.18);
$shadow-light: rgba(0, 0, 0, 0.05);
$shadow-medium: rgba(0, 0, 0, 0.1);

// 页面容器
.login-page {
  min-height: 100vh;
  position: relative;
  overflow: hidden;
  background: $background-primary;
}

// 动态背景
.background-layer {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 1;

  .gradient-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(
      135deg,
      rgba(0, 122, 255, 0.05) 0%,
      rgba(90, 200, 250, 0.03) 50%,
      rgba(52, 199, 89, 0.02) 100%
    );
  }

  .floating-elements {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;

    .float-element {
      position: absolute;
      border-radius: 50%;
      background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
      backdrop-filter: blur(20px);
      animation: float 20s infinite ease-in-out;

      &.element-1 {
        width: 120rpx;
        height: 120rpx;
        top: 15%;
        right: 10%;
        animation-delay: 0s;
      }

      &.element-2 {
        width: 80rpx;
        height: 80rpx;
        top: 45%;
        left: 8%;
        animation-delay: -5s;
      }

      &.element-3 {
        width: 100rpx;
        height: 100rpx;
        bottom: 30%;
        right: 15%;
        animation-delay: -10s;
      }

      &.element-4 {
        width: 60rpx;
        height: 60rpx;
        bottom: 15%;
        left: 20%;
        animation-delay: -15s;
      }
    }
  }
}

// 主容器
.main-container {
  position: relative;
  z-index: 2;
  min-height: 100vh;
  padding: 0 48rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

// 头部区域
.header-area {
  text-align: center;
  margin-bottom: 120rpx;
  opacity: 0;
  transform: translateY(-60rpx);
  transition: all 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94);

  &.visible {
    opacity: 1;
    transform: translateY(0);
  }

  .logo-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    margin-bottom: 40rpx;

    .logo-ring {
      width: 120rpx;
      height: 120rpx;
      background: linear-gradient(135deg, $primary-color, $secondary-color);
      border-radius: 32rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-bottom: 32rpx;
      box-shadow: 0 8rpx 32rpx rgba(0, 122, 255, 0.3);
      animation: pulse 3s infinite;

      .logo-image {
        width: 72rpx;
        height: 72rpx;
        filter: brightness(0) invert(1);
      }
    }

    .title-group {
      display: flex;
      flex-direction: column;
      align-items: center;

      .app-name {
        font-size: 56rpx;
        font-weight: 700;
        color: $text-primary;
        letter-spacing: -2rpx;
        margin-bottom: 8rpx;
      }

      .app-subtitle {
        font-size: 32rpx;
        font-weight: 500;
        color: $text-secondary;
        letter-spacing: 2rpx;
      }
    }
  }

  .welcome-text {
    font-size: 34rpx;
    font-weight: 500;
    color: $text-secondary;
  }
}

// 表单容器
.form-container {
  opacity: 0;
  transform: translateY(60rpx);
  transition: all 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) 0.2s;

  &.visible {
    opacity: 1;
    transform: translateY(0);
  }

  .form-card {
    background: rgba(255, 255, 255, 0.9);
    backdrop-filter: blur(20px);
    border-radius: 32rpx;
    padding: 64rpx 48rpx;
    box-shadow:
      0 20rpx 60rpx $shadow-light,
      0 8rpx 24rpx $shadow-medium;
    border: 1rpx solid rgba(255, 255, 255, 0.5);
  }
}

// 输入组
.input-group {
  margin-bottom: 48rpx;

  &.error .input-wrapper {
    border-color: $error-color;
    background: rgba(255, 59, 48, 0.05);
  }

  .input-wrapper {
    position: relative;
    display: flex;
    align-items: center;
    background: rgba(255, 255, 255, 0.8);
    border: 2rpx solid $border-color;
    border-radius: 20rpx;
    height: 112rpx;
    transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);

    &:focus-within {
      border-color: $primary-color;
      background: rgba(255, 255, 255, 1);
      box-shadow: 0 0 0 8rpx rgba(0, 122, 255, 0.1);
      transform: translateY(-4rpx);
    }
  }

  .input-prefix {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 80rpx;
    height: 100%;
  }

  .input-field {
    flex: 1;
    height: 100%;
    font-size: 34rpx;
    font-weight: 500;
    color: $text-primary;
    background: transparent;
    border: none;
    outline: none;

    &::placeholder {
      color: $text-tertiary;
      font-weight: 400;
    }
  }

  .input-suffix {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 80rpx;
    height: 100%;
    cursor: pointer;
    transition: all 0.2s ease;

    &:active {
      transform: scale(0.9);
    }
  }

  .error-message {
    display: block;
    font-size: 26rpx;
    color: $error-color;
    margin-top: 16rpx;
    margin-left: 24rpx;
    animation: shake 0.5s ease-in-out;
  }
}

// 验证码提示
.captcha-notice {
  display: flex;
  align-items: center;
  background: rgba(255, 149, 0, 0.1);
  border: 1rpx solid rgba(255, 149, 0, 0.3);
  border-radius: 16rpx;
  padding: 24rpx 32rpx;
  margin-bottom: 48rpx;

  .captcha-text {
    font-size: 28rpx;
    color: $warning-color;
    margin-left: 16rpx;
  }
}

// 登录按钮
.login-button {
  width: 100%;
  height: 112rpx;
  background: linear-gradient(135deg, $primary-color 0%, $secondary-color 100%);
  border: none;
  border-radius: 20rpx;
  font-size: 36rpx;
  font-weight: 600;
  color: #ffffff;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow:
    0 12rpx 40rpx rgba(0, 122, 255, 0.4),
    0 4rpx 16rpx rgba(0, 122, 255, 0.2);
  transition: all 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  position: relative;
  overflow: hidden;
  margin-bottom: 48rpx;

  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.3), transparent);
    transition: left 0.6s ease;
  }

  &:active:not(.disabled) {
    transform: translateY(4rpx) scale(0.98);
    box-shadow:
      0 6rpx 20rpx rgba(0, 122, 255, 0.4),
      0 2rpx 8rpx rgba(0, 122, 255, 0.3);

    &::before {
      left: 100%;
    }
  }

  &.loading {
    background: linear-gradient(
      135deg,
      lighten($primary-color, 10%),
      lighten($secondary-color, 10%)
    );
  }

  &.disabled {
    opacity: 0.7;
    cursor: not-allowed;
  }

  .button-content,
  .loading-content {
    display: flex;
    align-items: center;
    justify-content: center;

    .button-text {
      margin-left: 16rpx;
      font-size: 36rpx;
      font-weight: 600;
    }
  }

  .loading-icon {
    animation: spin 1s linear infinite;
  }
}

// 表单操作
.form-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .action-link {
    font-size: 30rpx;
    color: $text-secondary;
    transition: all 0.2s ease;

    &.primary {
      color: $primary-color;
      font-weight: 500;
    }

    &:active {
      opacity: 0.6;
      transform: scale(0.95);
    }
  }
}

// 租户信息
.tenant-info {
  margin-top: 48rpx;
  opacity: 0;
  transform: translateY(40rpx);
  transition: all 0.8s cubic-bezier(0.25, 0.46, 0.45, 0.94) 0.4s;

  &.visible {
    opacity: 1;
    transform: translateY(0);
  }

  .tenant-card {
    background: rgba(255, 255, 255, 0.6);
    backdrop-filter: blur(10px);
    border: 1rpx solid rgba(255, 255, 255, 0.3);
    border-radius: 20rpx;
    padding: 32rpx;
    display: flex;
    align-items: center;

    .tenant-label {
      font-size: 28rpx;
      color: $text-secondary;
      margin-left: 16rpx;
      margin-right: 16rpx;
    }

    .tenant-name {
      font-size: 28rpx;
      color: $text-primary;
      font-weight: 500;
    }
  }
}

// 页面装饰
.page-decoration {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  pointer-events: none;
  z-index: 0;

  .decoration-line {
    position: absolute;
    background: linear-gradient(45deg, transparent, rgba(0, 122, 255, 0.1), transparent);
    animation: move 15s infinite linear;

    &.line-1 {
      width: 2rpx;
      height: 200rpx;
      top: 20%;
      right: 20%;
    }

    &.line-2 {
      width: 200rpx;
      height: 2rpx;
      bottom: 30%;
      left: 10%;
      animation-delay: -7s;
    }
  }
}

// 动画定义
@keyframes float {
  0%,
  100% {
    transform: translateY(0px) rotate(0deg);
  }
  33% {
    transform: translateY(-30rpx) rotate(5deg);
  }
  66% {
    transform: translateY(20rpx) rotate(-3deg);
  }
}

@keyframes pulse {
  0%,
  100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes shake {
  0%,
  100% {
    transform: translateX(0);
  }
  25% {
    transform: translateX(-5rpx);
  }
  75% {
    transform: translateX(5rpx);
  }
}

@keyframes move {
  0% {
    transform: translateX(-100rpx);
    opacity: 0;
  }
  50% {
    opacity: 1;
  }
  100% {
    transform: translateX(200rpx);
    opacity: 0;
  }
}

// 响应式设计
@media (max-width: 750rpx) {
  .main-container {
    padding: 0 32rpx;
  }

  .form-card {
    padding: 48rpx 32rpx;
  }

  .header-area .logo-section .title-group .app-name {
    font-size: 48rpx;
  }

  .input-group .input-wrapper {
    height: 100rpx;
  }

  .login-button {
    height: 100rpx;
    font-size: 32rpx;
  }
}

// 页面加载状态
.login-page:not(.loaded) {
  .header-area,
  .form-container,
  .tenant-info {
    opacity: 0;
  }
}
</style>
